package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

type Miao2 struct {
	Id      int
	Cnt     int
	Version int
}

func main() {
	db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/db1")
	defer db.Close()

	if err != nil {
		fmt.Printf("connect to db 127.0.0.1:3306 error: %v\n", err)
		return
	}

	pinsertData(db, "INSERT INTO miao (cnt, version) VALUES (?, ?)", 33, 33)
	pselectData(db, "SELECT * From miao WHERE id = ?", 2)
}

func pinsertData(db *sql.DB, sql string, params ...interface{}) {
	stmt, _ := db.Prepare(sql)
	res, err := stmt.Exec(params...)
	defer stmt.Close()

	if err != nil {
		log.Fatalf("insert data error: %v\n", err)
	}
	affected, _ := res.RowsAffected()
	log.Printf("insert affected rows %v\n", affected)
	id, _ := res.LastInsertId()
	log.Printf("last insert ID %v\n", id)
}

func pselectData(db *sql.DB, sql string, params ...interface{}) {
	stmt, _ := db.Prepare(sql)
	rows, err := stmt.Query(params...)

	defer stmt.Close()
	defer rows.Close()

	if err != nil {
		log.Fatalf("select data error: %v\n", err)
		return
	}
	var res []Miao2
	for rows.Next() {
		var m Miao2
		rows.Scan(&m.Id, &m.Cnt, &m.Version)
		if err != nil {
			log.Fatal(err)
		}
		json, _ := json.Marshal(m)
		log.Printf("get data, %v\n", string(json))
		res = append(res, m)
	}
	err = rows.Err()
	if err != nil {
		log.Fatal(err)
	}
}
